<template>
  <view class="content">
    <view class="top">
      <customHeader></customHeader>
      <customSearch></customSearch>
    </view>
    <view class="center">
      <view class="sidebar-container">
        <treeSidebar 
          :data="treeData" 
          :selected-node="selectedNode"
          @node-click="handleNodeClick"
        ></treeSidebar>
      </view>
      <view class="right_content"> 
        <view class="table_content">
          <view style="padding-bottom: 40rpx;">
            <scroll-view :scroll-top="0" scroll-y="true" class="table_1_content">
              <t-table>
                <t-tr style=" position: sticky; top: 0; width: 100%; background: #fff; z-index: 2; " >
                  <t-th style="flex:0 0 250upx;">图片</t-th>
                  <t-th style="flex:0 0 150upx;word-break: break-all;">货号</t-th>
                  <t-th >名称</t-th>
                  <t-th style="flex:0 0 120upx;">装箱数量</t-th>
                  <t-th style="flex:0 0 100upx;">批发价</t-th>
                  <t-th style="flex:0 0 90upx;word-break: break-all;">/</t-th>
                </t-tr>
                <view  v-for="(item, index) in indexList" :key="index" @click="handleEnter(item)">
                  <t-tr>
                    <t-th style="flex:0 0 250upx;">
                      <image
                        mode="scaleToFill"
                        class="table_img"
                        :src="
                          item.files.length
                            ? item.files[0].url
                            : '../../static/none.png'
                        "
                      ></image>
                    </t-th>
                    <t-th style="flex:0 0 150upx;word-break: break-all;">{{ item.no }}</t-th>
                    <t-th >
                      <view class="bao_td_left">
                        {{ item.name }}
                      </view>
                    </t-th>
                    <t-th style="flex:0 0 120upx;  -webkit-line-clamp: 2;overflow: hidden; text-overflow: ellipsis; ">{{ item.units }}</t-th>
                    <t-th style="flex:0 0 100upx;">
                      {{ item.wholesale }}元/{{ item.unit_text }}
                    </t-th>
                    <t-th style="flex:0 0 90upx;word-break: break-all;"> 
                      <text
                        @click.stop="handleAddCar(item)"
                        class="iconfont icon-jiarugouwuche"
                      ></text>
                    </t-th>
                  </t-tr>
                </view>
                
              </t-table>
            </scroll-view>

          </view>

        </view>
        <view
          class="bottom_content"
          :style="{ left: sidebarBool ? '492rpx' : '0rpx' }"
        >
          <myPagination
            :key="selectedNode ? selectedNode.id : 'default'"
            style="height: 80rpx"
            :totalPage="totalCount"
            :pageIndex="pageindex"
            :changeCallback="parentCallback"
          >
          </myPagination>
        </view>
      </view>

    </view>

    <!-- 弹出框修改数量 -->
    <u-popup
      :show="showNumPopup"
      round="25"
      @close="showNumPopup = false"
      @open="showNumPopup = true"
      mode="center"
      :closeable="true"
    >
      <view class="popup_content">
        <view class="num">
          <view>数量：</view>
          <input v-model.number="num" type="number" />
        </view>
        <button hover-class="btn_hover" @click="handleAddCarNum">确定</button>

        <view v-if="showToast" class="toast">
          {{ showToastStr }}
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import { mapState, mapMutations, mapActions } from "vuex";

import customHeader from "@/components/custom-header/custom-header.vue";
import customSearch from "@/components/custom-search/custom-search.vue";
import treeSidebar from "@/components/custom-sidebar/tree-sidebar.vue";
import myPagination from "@/components/my-pagination/my-pagination.vue";
import tTable from '@/components/t-table/t-table.vue'
import tTh from '@/components/t-table/t-th.vue'
import tTr from '@/components/t-table/t-tr.vue'
import tTd from '@/components/t-table/t-td.vue'

import { shopType, tableInfo } from "@/api/modules/index.js";
import { findLevel, addNumField, setCheckedById } from "@/util/sidebarFn.js";

export default {
  components: {
    customHeader,
    customSearch,
    treeSidebar,
    myPagination,
    tTable,
    tTh,
    tTr,
    tTd,
  },
  data() {
    return {
      showNumPopup: false, // 弹出框
      num: 1,
      showToast: false, // 消息展示框
      showToastStr: "", // 提示框内容
      timer: "", // 展示毫秒数
      itemNumMap: {}, // 点击选中
      scrollTop: 0, // 滚动条
      
      treeData: [],
      selectedNode: null
    };
  },
  async onLoad() {
    await this._getShopType();
  },
  computed: {
    ...mapState([
      "sideList",
      "indexList",
      "keysearch",
      "pageindex",
      "pagesize",
      "sidebarBool",
      "totalCount",
    ]),
  },
  methods: {
    handleNodeClick(node) {
        // 设置选中的节点
        this.selectedNode = node;
        this._getShopType(node.id)
    },

    // 、、、、、、、、、、、、、、、、、、、、
		changeDataChecked(param) {
      // console.log('== 父', param)
      this.getSidebarId(param.id)
			let newSideData = setCheckedById(this.sideList, param.name)
      this.getSideData(JSON.parse(JSON.stringify(newSideData)))
      this.getTableDataAct(this.pageindex)
		},
    scrollPosition(e) {
      // 滚动事假
      // this.scrollTop = e.detail.scrollTop;
    },
    parentCallback(pageIndex) {
      //这里是页码变化后要做的事
      this.scrollTop = 0; // 回到顶部
      this.getTableDataAct({pageIndex, id: this.selectedNode.id});
    },
    handleAddCarNum() {
      if (this.num < 1) {
        this.changeData("数量不能小于 1");
        return;
      }
      let arr = [
        {
          ...this.itemNumMap,
          files: this.itemNumMap.files.length
            ? this.itemNumMap.files.map((i) => ({
                ...i,
                url: i.url ? i.url.split("wms")[1] : "",
              }))
            : [],
          num: Number(this.num),
          check: false,
          showGift: false, // 添加是否是赠品
        },
      ];
      this.addShopCar(arr);
      this.showNumPopup = false;
    },
    handleAddCar(item) {
      this.showNumPopup = true;
      this.itemNumMap = JSON.parse(JSON.stringify(item));
      this.num = 1;
    },
    scrolltolower() {
      // this.getTableDataAct(true);
    },
    handleEnter(param) {
      uni.navigateTo({
        url: `../productDetail/productDetail?param=${param.id}`,
      });
    },
    async _getShopType(id) {
      let param = {
        // type_nos: ['cp', 'bcp'],
        parent_id: id || '',
        // walk: 'true'
      };

      const res = await shopType(JSON.stringify(param));
      const {
        data: { status, message, data },
      } = res || {};

      if (status == "success") {
        if (!id) {
          let newData = (data || []).map((i, j) => ({
            ...i,
            expanded: false,
          }));
          this.treeData = newData
          if (newData.length > 0) {
            this.selectedNode = newData[0];
            this._getTableInfo(newData[0].id);
          }
        } else {
          let newData = (data || []).map((i, j) => ({
            ...i,
            expanded: false,
          }));
          // 使用递归函数更新指定节点的children
         this.updateTreeNodeChildren(id, newData);
         this._getTableInfo(id)
          
        }

      } else if (status === "fail") {
        uni.showToast({
          title: message,
          duration: 2000,
          icon: "none",
        });
      }
    },
    
    // 递归函数：在treeData中找到指定id的节点并更新其children
    updateTreeNodeChildren(targetId, childrenData) {
      // 参数验证
      if (!targetId || !Array.isArray(childrenData)) {
        return false;
      }
      
      // 递归查找并更新
      const updateNode = (nodes) => {
        for (let i = 0; i < nodes.length; i++) {
          const node = nodes[i];
          if (node.id === targetId) {
            this.$set(node, 'children', childrenData);
            return true; // 找到并更新成功
          }
          
          // 如果当前节点有子节点，递归查找
          if (node.children && node.children.length > 0) {
            if (updateNode(node.children)) {
              return true; // 在子节点中找到并更新成功
            }
          }
        }
        return false; // 未找到匹配的节点
      };
      // 执行递归更新
      updateNode(this.treeData);
    },
    async _getTableInfo(id) {
      let param = {
        paging: {
          pageIndex: 1,
          pageSize: this.pagesize,
        },
        query: {
          type_nos: ['cp', 'bcp', 'yl'],
          valid: true,
          cate_id: id || '',
          search: this.keysearch, // 搜索字段
        },
      };
      console.log('== param', param)
      const res = await tableInfo(JSON.stringify(param));
      const {
        data: {
          status,
          data: { paging, materiels },
          message,
        },
      } = res || {};
      // console.log('== res 列表详情', res)

      let newData = {
        list: materiels,
        totalCount: paging.total,
        totalPage: paging.pageIndex,
      };

      if (status == "success") {
        this.getTableData({ data: newData, keysearch: this.keysearch });
        this.getSidebarId(this.sideList[0]?.id)
      } else if (status === "fail") {
        uni.showToast({
          title: message,
          duration: 2000,
          icon: "none",
        });
      }
    },
    changeData(param) {
      // img 信息弹出框
      this.showToast = true;
      this.showToastStr = param;
      this.timer = setTimeout(() => {
        this.showToast = false;
        clearTimeout(this.timer);
      }, 1500);
    },
    onUnload() {
      this.unloadPage();
    },
    ...mapMutations([
      "getSideData",
      "getTableData",
      "unloadPage",
      "addShopCar",
      "getSidebarId"
    ]),
    ...mapActions(["getTableDataAct"]),
  },
};
</script>

<style lang="less" scoped>
.content {
  .top {
    position: fixed;
    width: 100%;
    z-index: 12;
  }

  .center {
    padding-top: 300rpx;
    display: flex;
    
    .sidebar-container {
      height: calc(100vh - 300rpx); /* 设置固定高度，减去顶部区域高度 */
      max-height: calc(100vh - 300rpx); /* 最大高度限制 */
      overflow-y: auto; /* 垂直滚动 */
      overflow-x: hidden; /* 隐藏水平滚动 */
      padding: 20rpx;
      box-sizing: border-box;
      /* 确保侧边栏不会超出视窗 */
      position: relative;
      
      /* 移动端滚动优化 */
      -webkit-overflow-scrolling: touch; /* iOS惯性滚动 */
      scroll-behavior: smooth; /* 平滑滚动 */
      
      /* 自定义滚动条样式 */
      &::-webkit-scrollbar {
        width: 8rpx;
      }
      
      &::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4rpx;
      }
      
      &::-webkit-scrollbar-thumb {
        background: #c1c1c1;
        border-radius: 4rpx;
      }
      
      &::-webkit-scrollbar-thumb:hover {
        background: #a8a8a8;
      }
    }
    
    .right_content {
      flex: 1;
      background: #fff;

      .table_content {
        margin: 0rpx 50rpx 0rpx 40rpx;

        .table_1_content {
          height: calc(100vh - 450rpx);
          width: 100%;

          .bao_td_left {
            width: 100%;
            height: 100%;
            text-align: left;
          }

          .table_img {
            width: 250rpx;
            height: 200rpx;
          }

          .icon-jiarugouwuche {
            font-size: 80rpx;
            color: #ef97a2;
          }
        }
      }







      .index_content {
        position: relative;
        height: calc(100vh - 298rpx);
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: center;

        .content_data {
          display: flex;
          flex-wrap: wrap;
          padding-bottom: 100rpx !important;
          // justify-content: flex-start; /* 设置主轴对齐方式为左对齐 */
          // justify-content: space-between;
          padding: 0 30rpx 30rpx;
          .item {
            width: 500rpx;
            background: #fff;
            margin: 0 12rpx;
            margin-bottom: 25rpx;
            image {
              width: 500rpx;
              height: 400rpx;
            }
            .title {
              display: -webkit-box;
              -webkit-line-clamp: 2;
              -webkit-box-orient: vertical;
              overflow: hidden;
              text-overflow: ellipsis;
            }
            .button_box {
              display: flex;
              justify-content: space-between;
              align-items: center;
              color: #ef97a2;
              .iconfont {
                font-size: 80rpx;
                margin-right: 20rpx;
              }
            }
          }
        }
      }
    }
  }

  .popup_content {
    position: relative;
    padding: 90rpx 40rpx 60rpx;
    .num {
      display: flex;
      align-items: center;
      input {
        border: 1rpx solid #ccc;
        padding: 10rpx 20rpx;
      }
    }

    button {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 80rpx;
      width: 200rpx;
      margin-top: 60rpx;
      background: #169bd5;
      color: #fff;
    }

    .btn_hover {
      background-color: #1589bb !important;
    }
    .toast {
      position: absolute;
      top: 0rpx;
      left: 180rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20rpx 40rpx;
      border-radius: 15rpx;
      background: #575757;
      color: #fff;
      font-size: 30rpx;
    }
  }

  // 底部
  .bottom_content {
    background: #fff;
    height: 100rpx;
    bottom: 0rpx;
    right: 0rpx;
    display: flex;
    align-items: center;
    // justify-content: center;
    transition: left 0.3s;
    padding-left: 40rpx;
  }
}
</style>
